<template>
    <div class="max-w-4xl mx-auto p-3 min-h-screen">
        <!-- 视频尺寸显示 -->
        <div class="text-gray-600 text-sm mb-2">
            视频尺寸: {{ store.videoDimensions.width > 0 ? `${store.videoDimensions.width}x${store.videoDimensions.height}px` : '加载中...' }}
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
                <!-- 左侧控制面板 -->
                <div class="space-y-3">
                    <!-- 裁剪参数设置 -->
                    <CropSettings />

                    <!-- 视频上传 -->
                    <VideoUploader @file-selected="processFile" />

                    <!-- 处理控制 -->
                    <ProcessingControls 
                        @start-processing="startProcessing"
                        @preview-frame="previewCurrentFrame"
                        @toggle-preview="handlePreviewToggle" />
                </div>
            </div>

            <div>
                <!-- 右侧视频和预览 -->
                <div class="space-y-3">
                    <!-- 视频预览 -->
                    <VideoPreview 
                        :isLooping="isLooping"
                        @update:videoElement="updateVideoElement"
                        @toggle-loop="toggleLoopPlay" />

                    <!-- 预览图片 -->
                    <div v-if="store.previewImageUrl" class="bg-white p-3 rounded-lg shadow">
                        <h3 class="text-md font-medium mb-1">当前帧预览:</h3>
                        <div class="flex justify-center" :style="{ backgroundColor: store.previewBgColor }">
                            <img :src="store.previewImageUrl" alt="预览图" class="max-w-full rounded" />
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 进度显示 -->
        <div class="mt-3">
            <ProgressDisplay />
        </div>
    </div>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted } from 'vue';
import { useVideoStore } from './stores/videoStore';
import CropSettings from './components/CropSettings.vue';
import VideoUploader from './components/VideoUploader.vue';
import ProcessingControls from './components/ProcessingControls.vue';
import VideoPreview from './components/VideoPreview.vue';
import ProgressDisplay from './components/ProgressDisplay.vue';
import { videoProcessor } from './utils/videoProcessor';
import { colorTools } from './utils/colorTools';
import { fileTools } from './utils/fileTools';
import { tools } from './utils/tools';

// 使用 Pinia store
const store = useVideoStore();

// 本地状态
const isLooping = ref(false);

// 初始化画布
const initCanvas = () => {
    try {
        if (!store.canvas) {
            store.canvas = document.createElement('canvas');
            if (!store.canvas) {
                throw new Error('无法创建画布元素');
            }
        }
        
        if (!store.ctx) {
            store.ctx = store.canvas.getContext('2d', { willReadFrequently: true });
            if (!store.ctx) {
                throw new Error('无法获取画布上下文');
            }
        }
        
        // 确保画布尺寸已设置
        if (store.videoDimensions.width > 0 && store.videoDimensions.height > 0) {
            store.canvas.width = store.cropParams.width || store.videoDimensions.width;
            store.canvas.height = store.cropParams.height || store.videoDimensions.height;
            console.log(`画布尺寸设置为: ${store.canvas.width}x${store.canvas.height}`);
        } else {
            console.warn('视频尺寸未知，无法设置画布尺寸');
        }
        
        return true;
    } catch (error) {
        console.error('初始化画布失败:', error);
        store.statusMessage = `初始化画布失败: ${error.message}`;
        return false;
    }
};

// 更新视频元素引用
const updateVideoElement = (element) => {
    store.sourceVideo = element;
    
    // 添加视频时间更新事件监听
    if (store.sourceVideo) {
        store.sourceVideo.addEventListener('timeupdate', handleTimeUpdate);
        
        // 当视频加载完成后，设置结束时间为视频总时长
        store.sourceVideo.addEventListener('loadedmetadata', () => {
            console.log('视频元数据加载完成，总时长:', store.sourceVideo.duration);
            if (store.endTime === 0) {
                store.endTime = store.sourceVideo.duration;
                console.log('设置结束时间为:', store.endTime);
            }
        });
    }
};

// 处理视频文件
const processFile = async (file) => {
    if (!file) return;
    
    store.videoFile = file;
    store.statusMessage = "正在加载视频...";
    
    // 如果已有视频源，先释放
    if (store.sourceVideo && store.sourceVideo.src) {
        URL.revokeObjectURL(store.sourceVideo.src);
    }
    
    // 创建视频对象URL
    const videoURL = URL.createObjectURL(file);
    
    // 设置视频源
    store.sourceVideo.src = videoURL;
    
    // 等待视频加载完成
    await new Promise((resolve) => {
        store.sourceVideo.onloadedmetadata = () => {
            // 更新视频尺寸
            store.videoDimensions = {
                width: store.sourceVideo.videoWidth,
                height: store.sourceVideo.videoHeight
            };
            
            // 设置默认裁剪参数为整个视频
            store.cropParams = {
                left: 0,
                top: 0,
                width: store.sourceVideo.videoWidth,
                height: store.sourceVideo.videoHeight
            };
            
            // 设置结束时间为视频总时长
            if (store.endTime === 0) {
                store.endTime = store.sourceVideo.duration;
            }
            
            store.statusMessage = "视频加载完成";
            resolve();
        };
        
        store.sourceVideo.onerror = () => {
            store.statusMessage = "视频加载失败";
            resolve();
        };
    });
};

// 使用防抖处理的预览函数
const debouncedPreview = tools.debounce(async () => {
    if (store.videoFile && store.sourceVideo && store.sourceVideo.readyState >= 2) {
        previewCurrentFrame();
    }
}, 300);

// 监听阈值变化，自动预览
watch([
    () => store.colorThreshold, 
    () => store.enableTransparency, 
    () => store.previewBgColor,
    () => store.colorHex
], debouncedPreview);

// 预览当前帧
const previewCurrentFrame = async () => {
    if (!store.videoFile || !store.sourceVideo) {
        alert('请先选择视频文件');
        return;
    }

    // 初始化画布
    initCanvas();

    if (!store.canvas || !store.ctx) {
        store.statusMessage = "无法创建画布";
        return;
    }

    try {
        // 更新目标颜色
        store.targetColor = colorTools.hexToRgb(store.colorHex);
        
        // 处理当前帧
        videoProcessor.processCurrentFrame({
            video: store.sourceVideo,
            canvas: store.canvas,
            ctx: store.ctx,
            cropParams: store.cropParams,
            enableTransparency: store.enableTransparency,
            targetColor: store.targetColor,
            threshold: store.colorThreshold
        });

        // 更新预览图片
        store.previewImageUrl = store.canvas.toDataURL('image/png');
        store.statusMessage = `已生成当前帧预览 (阈值: ${store.colorThreshold})`;

        // console.log('预览使用的阈值:', store.colorThreshold);
        // console.log('目标颜色:', store.targetColor);
    } catch (error) {
        console.error('预览生成失败:', error);
        store.statusMessage = "预览生成失败";
    }
};

// 循环播放控制
const toggleLoopPlay = () => {
    isLooping.value = !isLooping.value;
    
    if (!store.sourceVideo) {
        console.error('视频元素不存在');
        return;
    }
    
    if (isLooping.value) {
        // 设置视频到开始时间并播放
        store.sourceVideo.currentTime = store.startTime || 0;
        store.sourceVideo.play().catch(err => {
            console.error('播放失败:', err);
            isLooping.value = false;
        });
    } else {
        store.sourceVideo.pause();
    }
};

// 监听视频时间更新
const handleTimeUpdate = () => {
    if (!store.sourceVideo || !isLooping.value) return;
    
    store.currentTime = store.sourceVideo.currentTime;
    const loopEndTime = store.endTime > 0 ? store.endTime : store.sourceVideo.duration;
    
    // 如果当前时间超过结束时间，则回到开始时间
    if (store.currentTime >= loopEndTime) {
        store.sourceVideo.currentTime = store.startTime || 0;
    }
};

// 设置默认视频
const setDefaultVideo = async () => {
    try {
        const file = await fileTools.loadDefaultVideo('/mv.mp4');
        processFile(file);
    } catch (error) {
        console.error('加载默认视频失败:', error);
        store.statusMessage = '默认视频加载失败，请手动选择视频文件';
    }
};

// 开始处理视频
const startProcessing = async () => {
    if (!store.videoFile) {
        alert('请先选择视频文件');
        return;
    }

    try {
        // 确保视频尺寸已加载
        if (store.videoDimensions.width <= 0 || store.videoDimensions.height <= 0) {
            throw new Error('视频尺寸未加载，请等待视频加载完成');
        }
        
        // 初始化画布并检查结果
        const canvasInitialized = initCanvas();
        if (!canvasInitialized) {
            throw new Error('画布初始化失败');
        }
        
        // 确保目标颜色已正确设置
        store.targetColor = colorTools.hexToRgb(store.colorHex);
        console.log('开始处理，使用目标颜色:', store.targetColor);
        console.log('颜色阈值:', store.colorThreshold);
        console.log('帧间隔:', store.frameInterval);
        console.log('时间范围:', store.startTime, '至', store.endTime);
        
        // 重置帧数组
        store.frames = [];
        store.progressValue = 0;
        store.statusMessage = "准备处理视频...";
        
        // 添加延迟，确保UI更新
        await new Promise(resolve => setTimeout(resolve, 100));
        
        // 设置处理超时保护
        const processingTimeout = setTimeout(() => {
            console.warn('视频处理超时，可能已卡住');
            store.statusMessage = "处理似乎已卡住，请尝试调整参数后重试";
        }, 60000); // 60秒超时
        
        try {
            await videoProcessor.startVideoProcessing({
                videoFile: store.videoFile,
                sourceVideo: store.sourceVideo,
                canvas: store.canvas,
                ctx: store.ctx,
                initCanvas: initCanvas,
                cropParams: store.cropParams,
                frameInterval: store.frameInterval,
                enableTransparency: store.enableTransparency,
                targetColor: store.targetColor,
                colorThreshold: store.colorThreshold,
                startTime: store.startTime,
                endTime: store.endTime,
                onProgress: (progress, time, message, frame) => {
                    store.progressValue = progress;
                    store.currentTime = time;
                    store.statusMessage = message;
                    if (frame) store.frames.push(frame);
                    
                    // 每次进度更新时重置超时计时器
                    clearTimeout(processingTimeout);
                },
                onComplete: async () => {
                    clearTimeout(processingTimeout);
                    
                    try {
                        if (store.frames.length === 0) {
                            store.statusMessage = "处理完成，但未生成任何帧";
                            return;
                        }
                        
                        await fileTools.exportFramesAsZip(store.frames, (message) => {
                            store.statusMessage = message;
                        });

                        // 清理资源
                        if (store.sourceVideo && store.sourceVideo.src) {
                            URL.revokeObjectURL(store.sourceVideo.src);
                        }

                        const frameCount = store.frames.length;
                        store.frames = [];
                        store.statusMessage = `处理完成! 共导出 ${frameCount} 帧`;
                    } catch (error) {
                        console.error('导出帧时出错:', error);
                        store.statusMessage = "导出失败，请查看控制台获取详细信息";
                        alert('导出帧时出错，请查看控制台获取详细信息');
                    }
                }
            });
        } finally {
            clearTimeout(processingTimeout);
        }
    } catch (error) {
        console.error('视频处理失败:', error);
        store.statusMessage = `视频处理失败: ${error.message}`;
    }
};

onMounted(() => {
    // 加载默认视频
    setDefaultVideo();
});

// 预览播放控制
const previewInterval = ref(null);
const handlePreviewToggle = (isPlaying) => {
    if (isPlaying) {
        // 开始预览播放
        if (!store.videoFile || !store.sourceVideo) {
            alert('请先选择视频文件');
            return;
        }
        
        // 设置视频到开始时间
        store.sourceVideo.currentTime = store.startTime || 0;

        if (previewInterval.value) {
            clearInterval(previewInterval.value);
        }
        
        // 每隔一段时间生成预览
        previewInterval.value = setInterval(() => {
            previewCurrentFrame();
            
            // 更新视频时间
            const nextTime = store.sourceVideo.currentTime + 0.1;
            const loopEndTime = store.endTime > 0 ? store.endTime : store.sourceVideo.duration;
            
            // 如果到达结束时间，则回到开始时间
            if (nextTime >= loopEndTime) {
                store.sourceVideo.currentTime = store.startTime || 0;
            } else {
                store.sourceVideo.currentTime = nextTime;
            }
        }, 100); // 每100毫秒更新一次
    } else {
        // 停止预览播放
        if (previewInterval.value) {
            clearInterval(previewInterval.value);
            previewInterval.value = null;
        }
    }
};

// 在组件卸载时清除定时器
onUnmounted(() => {
    if (previewInterval.value) {
        clearInterval(previewInterval.value);
    }
});
</script>